package com.shareyi.wox.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.shareyi.wox.config.ActionBean;
import com.shareyi.wox.config.PackageBean;
import com.shareyi.wox.core.ActionConfig;
import com.shareyi.wox.core.WoxConfiguartion;
import com.shareyi.wox.core.WoxException;
import com.shareyi.wox.core.impl.DefaultConfiguaration;
import com.shareyi.simpleserver.core.HttpRequest;

public class PackageAndActionResolver {

	public static DefaultConfiguaration getConfiguration(WoxConfiguartion woxConfiguartion,HttpRequest request) throws WoxException{
		DefaultConfiguaration configuration=new DefaultConfiguaration();
		String namespace=request.getContextPath();
		String actionName=request.getUri();
		configuration.setActionName(actionName);
		configuration.setNamespace(namespace);
		return configuration;
	
	}

	
	public static void findPackageAndAction(WoxConfiguartion woxConfiguartion,DefaultConfiguaration configuaration) throws WoxException{
		 HashMap<String, List<PackageBean>>	namespaceMap=woxConfiguartion.getNamespaceMap();
		String namespace=configuaration.getNamespace();
		String actionName=configuaration.getActionName();
		List<PackageBean> packageBeans=namespaceMap.get(namespace);
		if(packageBeans==null){
			if(StringUtils.isNotEmpty(namespace)){
				packageBeans=namespaceMap.get(ActionConfig.DEFAULT_NAMESPACE);
			}
		}
		if(packageBeans==null||packageBeans.isEmpty()){
			throw new WoxException("cant not find action ["+actionName+"] in namespace \"\" and ["+namespace+"]");
		}
		
		ActionBean resultActionBean=null;
		
		
		WildcardHelper wildcardHelper=new WildcardHelper();
		outer:	for (PackageBean packageBean : packageBeans) {
			List<ActionBean> actionBeans=packageBean.getActionBeans();
				for (ActionBean actionBean : actionBeans) {
					Map<String,String> patternResult=actionBean.isMatchActionName(actionName,wildcardHelper);
					if(patternResult!=null){
						resultActionBean=actionBean;
						configuaration.setActionBean(resultActionBean);
						configuaration.setPatternResult(patternResult);
						configuaration.setActionName(actionName);
						configuaration.setMethodName(MatchHelper.methodNameMatcher(actionBean.getMethod(), patternResult));
						configuaration.setNamespace(namespace);
						configuaration.setPackageBean(packageBean);
						break outer;
					}
				}
		}
		
		
		if(resultActionBean==null){
			throw new WoxException("cant not find action ["+actionName+"] in namespace \"\" and ["+namespace+"]");
		}
		
	}


	
}
